package com.zg.common.dds;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author Zxb
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix="dds.default")
    public DataSource defaultDataSource(){
        HikariDataSource ds = DataSourceBuilder.create().type(HikariDataSource.class).build();
        DynamicDataSource.configDs(ds);
        return ds;
    }

    @Bean
    @Primary
    @DependsOn({"defaultDataSource"})
    public DataSource dynamicDataSource(
            @Qualifier("defaultDataSource") DataSource defaultDataSource){
        DynamicDataSource dds = new DynamicDataSource();
        dds.setDefaultTargetDataSource(defaultDataSource);
        dds.setTargetDataSources(DynamicDataSource.dataSourceMap);
        return dds;
    }
}
